package control

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"strconv"
	"strings"
	"time"

	. "gopkg.in/mgo.v2/bson"

	"gopkg.in/mgo.v2"
)

const (
	MGO_COLL_MSGPACKETS = "msgpackets"
)

func init() {
	http.Handle("/", http.FileServer(http.Dir("./web")))
	http.HandleFunc("/data/schpacket", schpacket)
}

// data := M{"clientid": sess.GetClientId(), "ip": sess.GetMQTTConner().RemoteAddr().String()}
// data["username"] = sess.GetConnectMessagePacket().GetUserNameByString()
// data["stime"] = time.Now()
// data["msgtype"] = packet.GetTypeName(msg.GetHeaderType())
// data["msg"] = msg.String()
// data["type"] = t
// data["datalen"] = msg.GetDataLen()
type packet struct {
	Id       []byte `bson:"_id"`
	Clientid string
	Ip       string
	Stime    time.Time
	Msgtype  string
	Msg      string
	Type     string
	Datalen  int
}
type packets struct {
	Datas     []*packet
	MaxCount  int
	CurPage   int
	TotalPage int
}

func schpacket(w http.ResponseWriter, r *http.Request) {
	r.ParseForm()

	curPage, _ := strconv.Atoi(r.FormValue("curPage"))
	count, _ := strconv.Atoi(r.FormValue("count"))
	clientid := r.FormValue("clientid")
	sendfrom := r.FormValue("sendfrom")
	packettype := r.FormValue("packettype")
	startdate := r.FormValue("startdate")
	enddate := r.FormValue("enddate")
	result := &packets{}
	if count == 0 {
		count = 10
	}
	if curPage <= 0 {
		curPage = 1
	}

	clientid = strings.TrimSpace(clientid)
	start := (curPage - 1) * count

	con := M{}

	if clientid != "" {
		con["clientid"] = M{"$regex": clientid}
	}
	switch sendfrom {
	case "c_s":
		con["type"] = "c_s"
	case "s_c":
		con["type"] = "s_c"
	}
	if packettype != "" {
		con["msgtype"] = packettype
	}
	timeM := M{}
	if startdate != "" {

		date, err := time.Parse("2006-01-02 15:04:05", startdate)
		if err == nil {
			con["stime"] = timeM
			timeM["$gte"] = date.Add(-8 * time.Hour)
		} else {
			Tlog.Debug("解析日期格式错误:", err)
		}

	}
	if enddate != "" {

		date, err := time.Parse("2006-01-02 15:04:05", enddate)
		if err == nil {

			con["stime"] = timeM
			timeM["$lte"] = date.Add(-8 * time.Hour)
		} else {
			Tlog.Debug("解析日期格式错误:", err)
		}
	}
	Tlog.Debug("查询条件:", con)
	err := GetMyMgo().ExecSync(MGO_COLL_MSGPACKETS, func(coll *mgo.Collection) error {

		sum, _ := coll.Find(con).Count()
		result.CurPage = curPage

		if sum == 0 {
			return nil
		}
		result.MaxCount = sum
		result.TotalPage = sum / count
		if sum%count != 0 {
			result.TotalPage++
		}
		var datas = make([]*packet, 0)
		err := coll.Find(con).Sort("-stime").Skip(start).Limit(count).All(&datas)
		if err != nil {
			return err
		}
		result.Datas = datas
		return nil
	})
	if err != nil {
		io.WriteString(w, fmt.Sprintf("读取数据失败:%v", err))
	}
	data, _ := json.Marshal(result)
	io.WriteString(w, string(data))
}
